package com.hmdp.utils;


import cn.hutool.core.lang.UUID;
import com.hmdp.service.ILock;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author yu yang
 * @date 2022/10/13 -19:52
 */
public class SimpleRedisLock implements ILock {
    private String keySubffix;
    private StringRedisTemplate stringRedisTemplate;
    private final String KEY_PREFIX = "lock:";
    private final String ID_PREFIX= UUID.randomUUID().toString(true)+"-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }
//    实现 拿锁比锁删锁的原子性动作了
    public void unLock() {
        // 调用lua脚本
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + keySubffix),
                ID_PREFIX + Thread.currentThread().getId());
    }

    public SimpleRedisLock(String keyId, StringRedisTemplate stringRedisTemplate) {
        this.keySubffix = keyId;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(Long timeSec) {
        //获取锁的标识
        String threadId = ID_PREFIX+Thread.currentThread().getId() ;
        //获取锁
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + keySubffix, threadId, timeSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(result);
    }

//    @Override
//    public void unLock() {
//        //获取当前线程的锁标识
//        String threadId = Thread.currentThread().getId() + ID_PREFIX;
//
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + keyId);
//
//        //与redis中的标识比较
//        if (threadId.equals(id)){
//            stringRedisTemplate.delete(KEY_PREFIX + keyId);
//        }
//
//    }
}
